/**
 * 
 */
package ro.dta.idbi.ui.patterns;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.JLabel;

import ro.dta.idbi.interfaces.sql.ISqlColumn;
import ro.dta.idbi.interfaces.sql.ISqlConstruct;
import ro.dta.idbi.interfaces.sql.ISqlTable;
import ro.dta.idbi.interfaces.ui.IMainFrame;
import ro.dta.idbi.patterns.ColToSupertypeRev;
import ro.dta.idbi.ui.sql.SqlColumnCell;
import ro.dta.idbi.ui.sql.SqlForeignKeyCell;
import ro.dta.idbi.ui.sql.SqlGraph;
import ro.dta.idbi.ui.sql.SqlTableCell;
import uk.ac.ic.doc.automed.reps.Schema;

import com.mxgraph.layout.hierarchical.mxHierarchicalLayout;
import com.mxgraph.model.mxGeometry;
import com.mxgraph.swing.mxGraphComponent;

/**
 * UI for the reverse transformation of the <i>column to supertype pattern</i>
 * 
 * @author Tudor Dobrila
 * 
 */
public class ColToSupertypeRevDialog extends AbstractPatternDialog {

	private static final long serialVersionUID = -6364709560727713008L;

	private static final Logger LOGGER = Logger
			.getLogger("ro.dta.idbi.ui.patterns.ColToSupertypeRevDialog");
	
	/**
	 * Check if the current pattern can be applied over a given set of objects
	 * 
	 * Used to check if the items selected by the user in the UI can be used to
	 * apply this transformation pattern over them
	 * 
	 * @param schema
	 *            Schema in the context of which to check the validity of the
	 *            array of objects
	 * @param objects
	 *            Set of objects
	 * @return True if pattern can be applied over set of objects, false
	 *         otherwise
	 */
	public static boolean isValid(final Schema schema, final Object[] objects) {
		if (objects.length < 2) {
			return false;
		}

		// Expect only tables and columns
		for (Object o : objects) {
			if (!(o instanceof ISqlTable) && !(o instanceof ISqlColumn)) {
				return false;
			}
		}

		// Get the column to be sent to the children
		ISqlColumn col = null;
		boolean hasCol = false;
		for (Object o : objects) {
			if (o instanceof ISqlColumn) {
				if (hasCol) {
					return false;
				}
				hasCol = true;
				col = (ISqlColumn) o;
			}
		}

		if (!hasCol || col.isPK()) {
			return false;
		}

		ISqlTable parentTbl = (ISqlTable) col.getParent();
		String parentName = parentTbl.getValue().toString();
		for (Object o : objects) {
			if (o instanceof ISqlTable) {
				ISqlTable crtTbl = (ISqlTable) o;
				if (!crtTbl.getSupertypesNames().contains(parentName)) {
					return false;
				}
			}
		}

		return true;
	}

	/**
	 * Reverse transformation for the <i>column to supertype pattern</i> dialog
	 * class constructor
	 * 
	 * @param parentFrame
	 *            Parent frame of this dialog
	 * @param schema
	 *            Schema over which the transformation is applied
	 * @param element
	 *            Sql construct(s) over which the transformation is applied
	 * @param beforeLabel
	 *            Label for the before diagram
	 * @param afterLabel
	 *            Label for the transformed diagram
	 */
	public ColToSupertypeRevDialog(final IMainFrame parentFrame, final Schema schema,
			final ISqlConstruct[] element, final JLabel beforeLabel, final JLabel afterLabel) {
		super(parentFrame, schema, element, beforeLabel, afterLabel);

		if (!isValid(schema, element)) {
			throw new IllegalArgumentException(
					"This pattern can't be applied to the given constructs.");
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see ro.dta.idbi.ui.patterns.AbstractTransDialog#createOriginalDiagram()
	 */
	@Override
	protected mxGraphComponent createOriginalDiagram() {
		initialise();
		final SqlGraph graph = new SqlGraph();
		graph.getModel().beginUpdate();

		try {
			SqlTableCell parentTbl = null;
			SqlTableCell[] newTables = new SqlTableCell[element.length];

			for (int i = 0; i < element.length; i++) {
				ISqlConstruct c = element[i];
				SqlTableCell newTbl = null;
				if (c instanceof ISqlTable) {
					newTbl = (SqlTableCell) c.clone();
				} else if (c instanceof ISqlColumn) {
					c.setStyle("SEL_COL");
					parentTbl = (SqlTableCell) c.getParent();
					newTbl = (SqlTableCell) parentTbl.clone();
					parentTbl = newTbl;
				}

				final mxGeometry newGeometry = new mxGeometry(5, 5, c.getGeometry().getWidth(), c
						.getGeometry().getHeight());
				newTbl.setGeometry(newGeometry);
				newTbl.layout(graph);
				newTables[i] = newTbl;
			}

			for (int i = 0; i < element.length; i++) {
				if (element[i] instanceof ISqlTable) {
					SqlForeignKeyCell foreignKey = new SqlForeignKeyCell(null, null, "", "", parentTbl,
							newTables[i], "FK_EDGE");
					graph.addCell(foreignKey, graph.getDefaultParent());
				}
			}
		} catch (CloneNotSupportedException e) {
			LOGGER.log(Level.SEVERE, "Fatal exception", e);
		} finally {
			final mxHierarchicalLayout layout = new mxHierarchicalLayout(graph);
			layout.execute(graph.getDefaultParent());
			graph.setAutoSizeCells(true);
			graph.getModel().endUpdate();
		}

		return new mxGraphComponent(graph);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * ro.dta.idbi.ui.patterns.AbstractTransDialog#createTransformedDiagram()
	 */
	@Override
	protected mxGraphComponent createTransformedDiagram() {
		final SqlGraph graph = new SqlGraph();
		graph.getModel().beginUpdate();

		try {
			SqlTableCell parentTbl = null;
			SqlTableCell[] newTables = new SqlTableCell[element.length];
			SqlColumnCell column = null;

			for (int i = 0; i < element.length; i++) {
				ISqlConstruct c = element[i];
				if (c instanceof ISqlColumn) {
					column = (SqlColumnCell) c;
				}
			}

			for (int i = 0; i < element.length; i++) {
				ISqlConstruct c = element[i];
				SqlTableCell newTbl = null;
				if (c instanceof ISqlTable) {
					newTbl = (SqlTableCell) c.clone();
					ISqlColumn column1 = (ISqlColumn) column.clone();
					column1.setStyle("COLUMN");
					newTbl.addColumn(column1);
				} else if (c instanceof ISqlColumn) {
					parentTbl = (SqlTableCell) c.getParent();
					newTbl = (SqlTableCell) parentTbl.clone();
					ISqlColumn column1 = newTbl.getColumn(column.getValue().toString());
					newTbl.removeColumn(column1);
					parentTbl = newTbl;
				}

				final mxGeometry newGeometry = new mxGeometry(5, 5, c.getGeometry().getWidth(), c
						.getGeometry().getHeight());
				newTbl.setGeometry(newGeometry);
				newTbl.relayout(graph);
				newTables[i] = newTbl;
			}

			for (int i = 0; i < element.length; i++) {
				if (element[i] instanceof ISqlTable) {
					SqlForeignKeyCell foreignKey = new SqlForeignKeyCell(null, null, "", "", parentTbl,
							newTables[i], "FK_EDGE");
					graph.addCell(foreignKey, graph.getDefaultParent());
				}
			}
		} catch (CloneNotSupportedException e) {
			LOGGER.log(Level.SEVERE, "Fatal exception", e);
		} finally {
			final mxHierarchicalLayout layout = new mxHierarchicalLayout(graph);
			layout.execute(graph.getDefaultParent());
			graph.setAutoSizeCells(true);
			graph.getModel().endUpdate();
		}

		return new mxGraphComponent(graph);
	}

	/**
	 * Initialise macro field
	 */
	private void initialise() {
		final StringBuilder cmd = new StringBuilder(ColToSupertypeRev.COMMAND);
		cmd.append(" (");
		for (ISqlConstruct c : element) {
			if (c instanceof ISqlColumn) {
				final SqlTableCell parentTable = (SqlTableCell) c.getParent();
				cmd.append("<<").append(parentTable.getValue()).append(",");
				cmd.append(c.getValue()).append(">>, ");
			}
		}
		for (ISqlConstruct c : element) {
			if (c instanceof ISqlTable) {
				cmd.append("<<").append(c.getValue()).append(">>, ");
			}
		}
		cmd.setLength(cmd.length() - 2);
		cmd.append(")");

		macroField.setText(cmd.toString());
	}

}
